package verificationcode

import (
	"fmt"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/cache"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/imageverificationcode"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/model"
	"github.com/gin-gonic/gin"
	"github.com/gomodule/redigo/redis"
	"go.uber.org/zap"
	"image/png"
	"net/http"
	"strconv"
)

const (
	REDIS_KEY_IMG_VERCODE = "ivc_" //图形验证码前缀
)

//=====================================
//校验图形验证码，单纯形的校验,函数形式，供其它代码调用
//
//=====================================
func CheckImgCodeFunc(deviceNo string, imgCode string) error {
	if deviceNo == "" {
		return fmt.Errorf("未发现身份标识")
	}
	if imgCode == "" {
		return fmt.Errorf("请输入图形验证码")
	}

	imgVerCodeInCache, _ := redis.String(cache.Do("GET", REDIS_KEY_IMG_VERCODE+deviceNo))
	if imgCode != imgVerCodeInCache {
		return fmt.Errorf("请输入正确的图形验证码")
	}
	cache.Do("DEL", REDIS_KEY_IMG_VERCODE+deviceNo) //校验无误后删除
	return nil
}

//=====================================
//校验图形验证码，单纯形的校验,接口形式，供网络访问
//区别于其它附属于业务中的验证逻辑，独立出来
//POST  答案缓冲10分钟，过期删除
//=====================================
func CheckImgCode(c *gin.Context) {
	deviceNo := c.PostForm("deviceNo")
	imgCode := c.PostForm("imgCode")
	if deviceNo == "" {
		c.JSON(http.StatusOK, model.Fail("未发现身份标识"))
		return
	}
	if imgCode == "" {
		c.JSON(http.StatusOK, model.Fail("请输入图形验证码"))
		return
	}

	imgVerCodeInCache, _ := redis.String(cache.Do("GET", REDIS_KEY_IMG_VERCODE+deviceNo))
	if imgCode != imgVerCodeInCache {
		c.JSON(http.StatusOK, model.Fail("请输入正确的图形验证码"))
		return
	}
	cache.Do("DEL", REDIS_KEY_IMG_VERCODE+deviceNo) //校验无误后删除
	c.JSON(http.StatusOK, model.Success("success"))
}

/**
获取图形验证码
参数默认为140,80
*/
func ImgVerCode(c *gin.Context) {
	var err error
	widthInt := 140
	heightInt := 80

	writer := c.Writer
	writer.Header().Set("Content-Type", "image/png")
	width := c.Param("w")
	height := c.Param("h")
	deviceNo := c.Param("deviceNo")
	if width != "" {
		widthInt, err = strconv.Atoi(width)
		if err != nil {
			global.Log.Warn("输入的宽度值 转换错误", zap.Any("err", err))
			widthInt = 140
		}
	}
	if height != "" {
		heightInt, err = strconv.Atoi(height)
		if err != nil {
			global.Log.Warn("输入的高度值 转换错误", zap.Any("err", err))
		}
	}

	global.Log.Info("开始创建图片验证码 ", zap.Any("宽度=", widthInt),
		zap.Any("高度=", heightInt), zap.Any("deviceNo=", deviceNo))
	img, answer := imageverificationcode.CreateImgVerCode(widthInt, heightInt)
	global.Log.Info("生成验证码:", zap.Any("answer", answer))

	if img == nil || answer == "" {
		global.Log.Warn("CreateImgVerCode 创建验证码图片错误")
	}
	//改成存储在内存中,key为唯一设备号,超时时间默认10分钟
	/*	_,err = cache.Do("SETEX", REDIS_KEY_IMG_VERCODE+deviceNo, 10*60, answer)
		if err != nil {
			c.JSON(http.StatusOK, model.Fail("生成图片错误,"+err.Error()))
			return
		}*/

	err = png.Encode(writer, img)
	if err != nil {
		c.JSON(http.StatusOK, model.Fail("生成图片错误,"+err.Error()))
		return
	}
	c.JSON(http.StatusOK, model.Success("生成图片验证码成功"))
	return
}
